package com.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.health.constant.MessageConstant;
import com.health.dao.*;
import com.health.entity.PageResult;
import com.health.entity.QueryPageBean;
import com.health.entity.Result;
import com.health.pojo.*;
import com.health.service.OrderService;
import com.health.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * @Classname OrderServiceImpl
 * @Description TODO
 * @Version 1.0.0
 * @Date 2023/3/18 18:06
 * @Author RainGrd
 */
@Service(interfaceClass = OrderService.class)
@Transactional
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderDao orderDao;


    @Autowired
    private UserDao userDao;

    @Autowired
    private MemberDao memberDao;

    @Autowired
    private SetmealDao setmealDao;

    @Autowired
    private ReportDao reportDao;


    @Autowired
    private OrderSettingDao orderSettingDao;

    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    public Result deleteOrderSettings(OrderList orderList) {
        //手机号码
        Member member = memberDao.findByTelephone(orderList.getPhoneNumber());
        //查询出来的会员
        Integer memberId = member.getId();
        //获取会员ID
        log.info("memberId:{}", memberId);
        //根据预约日期查询预约对象
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(orderList.getOrderDate());
        //修改已预约人数
        orderSetting.setReservations(orderSetting.getReservations() - 1);
        //修改已预约人数
        orderSetting.setNumber(orderSetting.getNumber() + 1);
        orderSettingDao.updateOrderSettingByOrderDate(orderSetting);
        log.info("取消预约的orderSetting:{}", orderSetting);
        //判断此预约是否已经到诊
        /*if (orderList.getOrderStatus().equals(Order.ORDERSTATUS_YES)) {
            //已经到诊，判断体检报告是否被下载
            Report report = reportDao.selectByMemberId(memberId);
            if (report == null) {
                return Result.error("该预约已经上传,请联系健康管理师上传体检报告");
            }
            log.info(String.valueOf(report.getReportStatus()));
            log.info("report.getReportStatus()!=2:{}", report.getReportStatus() != 2);
            //判断体检报告
            if (report.getReportStatus() != 2) {
                return Result.error("该会员还没有下载体检报告，请先不要取消预约");
            }
        }*/
        try {
            //根据Id删除预约对象
            int i = orderDao.deleteById(orderList.getId());
            //根据会员Id与套餐Id删除体检报告
            reportDao.deleteByMemberIdAndSetmealId(orderList.getMemberId(), orderList.getSetmealId());
            //根据会员Id删除会员对象
//            memberDao.deleteMemberById(memberId);
            //如果调用失败就进入catch，没有失败就
            return i > 0 ? Result.success() : Result.error();
        } catch (Exception e) {
            //证明调用失败
            e.printStackTrace();
            return Result.error();
        }

    }

    @Override
    public PageResult queryOrderForPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        List<Setmeal> setmealList = setmealDao.selectByCondition(queryPageBean.getQueryString());
        long total = setmealDao.selectTotalByCondition(queryPageBean.getQueryString());
        return new PageResult(total, setmealList);
    }

    @Override
    public Result saveOrder(Map<String, String> map) {
        try {
            String userId = map.get("userId");
            //检查当前日期是否进行了预约设置
            String orderDate = map.get("orderDate");
            String name = map.get("name");
            if (userId != null) {
                //发送邮件
                sendMailUser(userId, DateUtils.parseDate2String(DateUtils.parseString2Date(orderDate)), name);
            }
            //设定预约类型
            map.put("orderType", Order.ORDER_TYPE_EMAIL);
            Date date = DateUtils.parseString2Date(orderDate);
            OrderSetting orderSetting = orderSettingDao.findByOrderDate(date);
            log.info("根据预约日期查询预约设置信息:{}", orderSetting);
            if (orderSetting == null) {
                return Result.error(MessageConstant.SELECTED_DATE_CANNOT_ORDER);
            }
            //检查预约日期是否预约已满
            int number = orderSetting.getNumber();//可预约人数
            int reservations = orderSetting.getReservations();//已预约人数
            if (reservations >= number) {
                //预约已满，不能预约
                return Result.error(MessageConstant.ORDER_FULL);
            }
            //检查当前用户是否为会员，根据手机号判断
            String telephone = map.get("telephone");
            log.info("取出的手机号:{}", telephone);
            Member member = memberDao.findByTelephone(telephone);
            //防止重复预约
            if (member != null) {
                Integer memberId = member.getId();
                int setmealId = Integer.parseInt(map.get("setmealId"));
                //查询是否存在重复预约
                Order order = new Order(memberId, null, null, null, setmealId);
                log.info("order:{}", order);
                List<Order> list = orderDao.findByCondition(order);
                log.info("list:{}", list);
                if (list != null && list.size() > 0) {
                    //已经完成了预约，不能重复预约
                    return Result.error(MessageConstant.HAS_ORDERED);
                } /*else {
                    //返回提示
                    return Result.error(MessageConstant.MEMBER_REPETITION);
                }*/
            }
            //可以预约，设置已预约人数加一
            orderSetting.setReservations(orderSetting.getReservations() + 1);
//            orderSettingDao.updateReservationsByOrderDate(orderSetting);
            //修改可预约人数
            orderSetting.setNumber(orderSetting.getNumber() - 1);
            orderSettingDao.updateOrderSettingByOrderDate(orderSetting);
            if (member == null) {
                //当前用户不是会员，需要添加到会员表
                member = new Member();
                member.setName(map.get("name"));
                member.setPhoneNumber(telephone);
                member.setIdCard(map.get("idCard"));
                member.setSex(map.get("sex"));
                member.setRegTime(new Date());
                memberDao.insertMember(member);
            }
            //保存预约信息到预约表
            Order order = new Order(member.getId(),
                    date,
                    map.get("orderType"),
                    Order.ORDERSTATUS_NO,
                    Integer.parseInt(map.get("setmealId")), Integer.parseInt(userId));
            orderDao.add(order);
            return Result.success(order.getId(), MessageConstant.ORDER_SUCCESS);
        } catch (Exception e) {
            log.error(e.getMessage());
            return Result.error();
        }
    }

    private void sendMailUser(String userId, String orderDate, String name) throws Exception {

        //查询用户
        User user = userDao.selectUserByKey(Integer.valueOf(userId));
        log.info("查询出来的用户:{}", user);
        MimeMessage mMessage = javaMailSender.createMimeMessage();//创建邮件对象
        MimeMessageHelper mMessageHelper;
        Properties prop = new Properties();
        String from;
        //从配置文件中拿到发件人邮箱地址
        prop.load(this.getClass().getResourceAsStream("/mail.properties"));
        from = prop.get("mail.smtp.username") + "";
        mMessageHelper = new MimeMessageHelper(mMessage, true);
        mMessageHelper.setFrom(from);//发件人邮箱
        mMessageHelper.setTo(user.getEmail());//收件人邮箱
        mMessageHelper.setSubject("客户体检信息健康管理系统");//邮件的主题
        //邮件的文本内容，true表示文本以html格式打开
        mMessageHelper.setText("<!DOCTYPE html>\n" +
                        "<html lang=\"en\" xmlns:th=\"http://www.thymeleaf.org\">\n" +
                        "<head>\n" +
                        "    <meta charset=\"UTF-8\">\n" +
                        "    <title>邮箱验证码</title>\n" +
                        "    <style>\n" +
                        "        table {\n" +
                        "            width: 700px;\n" +
                        "            margin: 0 auto;\n" +
                        "        }\n" +
                        "\n" +
                        "        #top {\n" +
                        "            width: 700px;\n" +
                        "            border-bottom: 1px solid #ccc;\n" +
                        "            margin: 0 auto 30px;\n" +
                        "        }\n" +
                        "\n" +
                        "        #top table {\n" +
                        "            font: 12px Tahoma, Arial, 宋体;\n" +
                        "            height: 40px;\n" +
                        "        }\n" +
                        "\n" +
                        "        #content {\n" +
                        "            width: 680px;\n" +
                        "            padding: 0 10px;\n" +
                        "            margin: 0 auto;\n" +
                        "        }\n" +
                        "\n" +
                        "        #content_top {\n" +
                        "            line-height: 1.5;\n" +
                        "            font-size: 14px;\n" +
                        "            margin-bottom: 25px;\n" +
                        "            color: #4d4d4d;\n" +
                        "        }\n" +
                        "\n" +
                        "        #content_top strong {\n" +
                        "            display: block;\n" +
                        "            margin-bottom: 15px;\n" +
                        "        }\n" +
                        "\n" +
                        "        #content_top strong span {\n" +
                        "            color: #f60;\n" +
                        "            font-size: 16px;\n" +
                        "        }\n" +
                        "\n" +
                        "        #verificationCode {\n" +
                        "            color: #f60;\n" +
                        "            font-size: 24px;\n" +
                        "        }\n" +
                        "\n" +
                        "        #content_bottom {\n" +
                        "            margin-bottom: 30px;\n" +
                        "        }\n" +
                        "\n" +
                        "        #content_bottom small {\n" +
                        "            display: block;\n" +
                        "            margin-bottom: 20px;\n" +
                        "            font-size: 12px;\n" +
                        "            color: #747474;\n" +
                        "        }\n" +
                        "\n" +
                        "        #bottom {\n" +
                        "            width: 700px;\n" +
                        "            margin: 0 auto;\n" +
                        "        }\n" +
                        "\n" +
                        "        #bottom div {\n" +
                        "            padding: 10px 10px 0;\n" +
                        "            border-top: 1px solid #ccc;\n" +
                        "            color: #747474;\n" +
                        "            margin-bottom: 20px;\n" +
                        "            line-height: 1.3em;\n" +
                        "            font-size: 12px;\n" +
                        "        }\n" +
                        "\n" +
                        "        #content_top strong {\n" +
                        "            font-size: 20px;\n" +
                        "        }\n" +
                        "\n" +
                        "        #content_top strong span {\n" +
                        "            font-size: 25px;\n" +
                        "            color: #FE4F70;\n" +
                        "        }\n" +
                        "\n" +
                        "        #sign {\n" +
                        "            text-align: right;\n" +
                        "            font-size: 18px;\n" +
                        "            color: #FE4F70;\n" +
                        "            font-weight: bold;\n" +
                        "        }\n" +
                        "\n" +
                        "        #verificationCode {\n" +
                        "            height: 100px;\n" +
                        "            width: 680px;\n" +
                        "            text-align: center;\n" +
                        "            margin: 30px 0;\n" +
                        "        }\n" +
                        "\n" +
                        "        #verificationCode div {\n" +
                        "            height: 100px;\n" +
                        "            width: 680px;\n" +
                        "\n" +
                        "        }\n" +
                        "\n" +
                        "        .button {\n" +
                        "            color: #FE4F70;\n" +
                        "            margin-left: 10px;\n" +
                        "            height: 80px;\n" +
                        "            width: 300px;\n" +
                        "            resize: none;\n" +
                        "            font-size: 42px;\n" +
                        "            border: none;\n" +
                        "            outline: none;\n" +
                        "            padding: 10px 15px;\n" +
                        "            background: #ededed;\n" +
                        "            text-align: center;\n" +
                        "            border-radius: 17px;\n" +
                        "            box-shadow: 6px 6px 12px #cccccc,\n" +
                        "            -6px -6px 12px #ffffff;\n" +
                        "        }\n" +
                        "\n" +
                        "        .button:hover {\n" +
                        "            box-shadow: inset 6px 6px 4px #d1d1d1,\n" +
                        "            inset -6px -6px 4px #ffffff;\n" +
                        "        }\n" +
                        "\n" +
                        "    </style>\n" +
                        "</head>\n" +
                        "<body>\n" +
                        "<table>\n" +
                        "    <tbody>\n" +
                        "    <tr>\n" +
                        "        <td>\n" +
                        "            <div id=\"top\">\n" +
                        "                <table>\n" +
                        "                    <tbody>\n" +
                        "                    <tr>\n" +
                        "                        <td></td>\n" +
                        "                    </tr>\n" +
                        "                    </tbody>\n" +
                        "                </table>\n" +
                        "            </div>\n" +
                        "\n" +
                        "            <div id=\"content\">\n" +
                        "                <div id=\"content_top\">\n" +
                        "                    <strong>尊敬的健康管理师： " + user.getUsername() + " 您好！</strong>\n" +
                        "                    <strong>\n" +
                        "                        您有一份来自患者<span>" + name + "</span>的预约请求\n" +
                        "                    </strong>\n" +
                        "                    <div id=\"verificationCode\">\n" +
                        "                        预约日期:\n" +
                        "                        <button class=\"button\">" + orderDate + "</button>\n" +
                        "                    </div>\n" +
                        "                </div>\n" +
                        "            </div>\n" +
                        "            <div id=\"bottom\">\n" +
                        "                <div>\n" +
                        "                    <p>此为系统邮件，请勿回复<br>\n" +
                        "                        请保管好您的邮箱，避免账号被他人盗用\n" +
                        "                    </p>\n" +
                        "                </div>\n" +
                        "            </div>\n" +
                        "        </td>\n" +
                        "    </tr>\n" +
                        "    </tbody>\n" +
                        "</table>\n" +
                        "</body>\n"
                , true);
        javaMailSender.send(mMessage);//发送邮件

    }


}
